// $engines.all().map((ScriptEngine) => {
//   if ($engines.myEngine().toString() !== ScriptEngine.toString()) {
//     ScriptEngine.forceStop();
//   }
// });
toastLog("yashu easyedge v3");
const execution = $engines.execScriptFile("./server/index.js", {
  arguments: {
    serverEngineId: $engines.myEngine().id,
  },
});

sleep(1000);
function kill(pid) {
  android.os.Process.killProcess(pid);
}
setTimeout(function () {
  // 请求截图
  if (!requestScreenCapture()) {
    toastLog("请求截图失败");
    setTimeout(function () {
      var nowPid = android.os.Process.myPid();
      var am = context.getSystemService(java.lang.Class.forName("android.app.ActivityManager"));
      var list = am.getRunningAppProcesses();
      for (var i = 0; i < list.size(); i++) {
        var info = list.get(i);
        if (info.pid != nowPid) {
          kill(info.pid);
        }
      }
      kill(nowPid);
      java.lang.System.exit(0);
    }, 666);
  }
}, 666);
let easyedge = require("./easyedge");

// 监听来自Node.js引擎发送的消息
$events.on("reply", (data) => {
  console.log("接收到消息 reply");
  console.log("data = " + data);
  // const params = {
  //   action: "ocr",
  //   imgPath: imgPath,
  // };
  if (data.action === "ocr") {
    let ocrResult = easyedge(data.imgPath);
    // let ocrResult = { xxx: "dddddddddddddddddddddd" };
    // 给Node.js引擎发送消息
    console.log("发送消息 ocrResult");
    execution.engine.emit("ocrResult", {
      action: "ocr",
      result: ocrResult,
    });
  } else if (data.action === "captureScreenOCR") {
    var img = captureScreen();
    let rectType = Object.prototype.toString.call(data.rect);
    log("rectType = " + rectType);
    log("data.rect = " + data.rect);
    if (data.rect) {
      var clip = images.clip(img, data.rect[0], data.rect[1], data.rect[2], data.rect[3]);
      let ocrResult = easyedge(null, clip);
      console.log("发送消息 ocrResult");
      execution.engine.emit("ocrResult", {
        action: "captureScreenOCR",
        result: ocrResult,
      });
    } else {
      let ocrResult = easyedge(null, img);
      console.log("发送消息 ocrResult");
      execution.engine.emit("ocrResult", {
        action: "captureScreenOCR",
        result: ocrResult,
      });
    }
  }
});

setInterval(function () {}, 9000);
